package graphics;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;

import controller.Constants;
import data.DrawingSettings;

/**
 * Eraser
 * 
 * @author Jie Zhao(288645)
 * 
 */
public class Eraser extends FreeDraw {
	private Color color = null;
	private Stroke stroke = null;

	public Eraser() {
		updateEraser();
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("eraser:");
		sb.append(getLineColor().getRGB()+":");
		sb.append((isFilled()?"1":"0") + ":");
		sb.append(getFilledColor().getRGB()+":");
		sb.append(getStroke().getLineWidth()+":");
		int[][] point = producePointsSet();
		for(int i=0;i<getNumofPoints();i++)
		{
			sb.append(point[0][i]+","+point[1][i]);
			if(i<getNumofPoints())sb.append(":");
		}
		return sb.toString();
	}

	@Override
	public void fromString(String str) {
		try{
		String[] data = str.split(":");
		if(!data[0].equals("eraser"))return;
		setLineColor(new Color(Integer.parseInt(data[1])));
		setFilled(data[2].equals("1"));
		setFilledColor(new Color(Integer.parseInt(data[3])));
		setStroke(new BasicStroke(Float.parseFloat(data[4]),BasicStroke.CAP_ROUND,BasicStroke.CAP_ROUND));
		String point[] = null;
		for(int i=5;i<data.length;i++)
		{
			point = data[i].split(",");
			addPoint(new Point(Integer.parseInt(point[0]),Integer.parseInt(point[1])));
		}
		}catch(Exception e)
		{
			if(Constants.DEBUG)e.printStackTrace();
		}
	}
	@Override
	/**
	 * Draw the eraser
	 */
	public void draw(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;
		g2d.setStroke(stroke);
		g2d.setColor(color);
		int[][] pointSet = producePointsSet();
		g2d.drawPolyline(pointSet[0], pointSet[1], getNumofPoints());
	}

	/**
	 * update the eraser setting if the setting has been changed
	 */
	public void updateEraser() {
		color = DrawingSettings.getInstance().getCanvasBackground();
		stroke = DrawingSettings.getInstance().getEraserSize();
	}
}
